<?php
/*
+--------------------------------------------------------------------------
|   Anwsion [#RELEASE_VERSION#]
|   ========================================
|   by Tatfook Network Team
|   (c) 2011 - 2012 Anwsion Software
|   http://www.anwsion.com
|   ========================================
|   Support: zhengqiang@gmail.com
|   
+---------------------------------------------------------------------------
*/

class db_manage_class extends AWS_MODEL
{
	var $backup_dir;

	public function setup()
	{
		$backup_dir = get_setting('backup_dir');
		
		if (! $backup_dir)
		{
			$backup_dir = random(4);
			@mkdir('./data/backup_' . $backup_dir, 0777);
			$this->model('setting')->set_vars(array(
				'backup_dir' => $backup_dir
			));
			$this->model('setting')->update_setting_config();
		}
		
		$this->backup_dir = 'backup_' . $backup_dir;
		
		if (! is_dir('./system/' . $this->backup_dir))
		{
			mkdir('./system/' . $this->backup_dir, 0777);
		}
	}
	
	public function get_backup_dir()
	{
		return $this->backup_dir;
	}

	function get_table_list()
	{
		$tablepre = $this->get_prefix();
		
		$tables = $table = array();
		
		$query = $this->query_all("SHOW TABLE STATUS LIKE '" . $tablepre . "%'");
		
		foreach ($query as $key => $val)
		{
			$tables[] = $val['Name'];
		}
		
		return $tables;
	}

	function dump_tbl_struct($table)
	{
		$createtable = $this->query_row("SHOW CREATE TABLE $table");
		
		$tabledump .= $createtable['Create Table'];
		
		$tablestatus = $this->query_row("SHOW TABLE STATUS LIKE '$table'");
		
		$tabledump .= ";\n\n";
		
		return $tabledump;
	}

	function dump_tbl_record($table, $sizelimit, $startfrom = 0, $complete = 0, $currsize = 0)
	{
		$offset = 300;
		$tabledump = '';
		$tablefields = array();
		
		$tablefields = $this->query_all("SHOW FULL COLUMNS FROM $table");
		
		$tabledumped = 0;
		$numrows = $offset;
		$firstfield = $tablefields[0];
		while ($currsize + strlen($tabledump) + 500 < $_GET['sizelimit'] * 1000 && $numrows == $offset)
		{
			if ($firstfield['Extra'] == 'auto_increment')
			{
				$selectsql = "SELECT * FROM $table WHERE $firstfield[Field] > $startfrom ORDER BY $firstfield[Field] LIMIT $offset";
			}
			else
			{
				$selectsql = "SELECT * FROM $table LIMIT $startfrom, $offset";
			}
			
			$tabledumped = 1;
			
			$rows = $this->query_all($selectsql);
			
			$numrows = count($rows);
			
			foreach ($rows as $row)
			{
				$comma = $t = '';
				
				foreach ($row as $key => $val)
				{
					$t .= $comma . ($_GET['usehex'] && ! empty($val) && (strpos($tablefields[$key]['Type'], 'char') || strpos($tablefields[$key]['Type'], 'text')) ? '0x' . bin2hex($val) : '\'' . mysql_escape_string($val) . '\'');
					$comma = ',';
				}
				
				if (strlen($t) + $currsize + strlen($tabledump) + 500 < $_GET['sizelimit'] * 1000)
				{
					if ($firstfield['Extra'] == 'auto_increment')
					{
						$startfrom = $row[$firstfield['Field']];
					}
					else
					{
						$startfrom ++;
					}
					
					$tabledump .= "INSERT INTO $table VALUES ($t);\n";
				}
				else
				{
					$complete = FALSE;
					break 2;
				}
			}
		}
		
		$tabledump .= "\n";
		
		return array(
			'tabledump' => $tabledump, 
			'startfrom' => $startfrom, 
			'complete' => $complete
		);
	}

	public function save_sql_file($filename, $sqldump, $volume)
	{
		$backupfilename = './system/' . $this->backup_dir . '/' . str_replace(array(
			'/', 
			'\\', 
			'.', 
			"'"
		), '', $filename);
		
		$dumpfile = $backupfilename . "-%s" . '.sql';
		
		$sqldump = "# Anwsion Mysql Data Bak Vol-$volume\n" . "# Version: " . get_setting('db_version') . "\n" . "# Time: " . date("Y-m-d H:i") . "\n" . "# Table Prefix: " . $this->get_prefix() . "\n" . "# Anwsion: http://www.anwsion.com\n" . "# --------------------------------------------------------\n\n\n" . "SET NAMES utf8;\n\n" . $sqldump;
		
		$dumpfilename = sprintf($dumpfile, $volume);
		
		@$fp = fopen($dumpfilename, 'wb');
		
		@flock($fp, 2);
		
		$wcount = @fwrite($fp, $sqldump);
		
		@fclose($fp);
		
		return $wcount;
	}
}
